package org.skipper.swagger.spring.boot;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author shoujian
 * Date: 2020-01-08
 * Time: 11:19 上午
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {

    protected final Log log = LogFactory.getLog(getClass());

    private SwaggerProperties swaggerProperties;

    @Autowired
    public void setSwaggerProperties(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public Docket createRestApi() {

        List<ResponseMessage> responseMessageList = listAllResponseMessage();

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerProperties.getDocket().getEnable())
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     * 遍历获取所有错误码（统一只处理TagCodeEnum中的code码）
     *
     * @return 错误码列表
     */
    private List<ResponseMessage> listAllResponseMessage() {

        List<ResponseMessage> responseMessageList = new ArrayList<>();

        if (swaggerProperties.getTagCode().getName() == null) {
            return responseMessageList;
        }
        try {

            Class<Enum> clz = (Class<Enum>) Class.forName(swaggerProperties.getTagCode().getName());

            Object[] objects = clz.getEnumConstants();

            Field[] fields = clz.getDeclaredFields();

            String getCodeMethod = "";
            String getMessageMethod = "";

            for (Field field : fields) {
                if (field.getType().getName().endsWith("String")) {
                    if ("".equals(getCodeMethod)) {
                        String fieldName = field.getName();
                        getCodeMethod = "get" + fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1));
                    } else if ("".equals(getMessageMethod)) {
                        String fieldName = field.getName();
                        getMessageMethod = "get" + fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1));
                    } else {
                        break;
                    }
                }
            }


            Method getCode = clz.getMethod(getCodeMethod);
            Method getMessage = clz.getMethod(getMessageMethod);

            for (Object obj : objects) {
                responseMessageList.add(new ResponseMessageBuilder()
                        .code(Integer.parseInt((String) getCode.invoke(obj)))
                        .message((String) getMessage.invoke(obj))
                        .build());
            }


        } catch (Exception e) {
            log.warn("not find TagCodeEnum");
        }
        return responseMessageList;
    }

    /**
     * 获取token参数配置
     *
     * @return token配置
     */
    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("token", "token", "header"));
        return apiKeyList;
    }

    /**
     * 通过正则表达式设置需要使用token的接口（暂时不用）
     *
     * @return 列表
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("米络科技spring cloud相关接口api文档")
                .description("统一管理api")
                .contact("root")
                .version("1.0")
                .build();
    }

}
